<?php
/**
 * Created by PhpStorm
 * @Author: wangwin
 * @Date: 2024/8/12
 * @Time: 9:29
 * @Version: 1.0
 */

namespace App\Service;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use TheSeer\Tokenizer\Exception;

class PaperService
{
    /**
     * 导入excel
     * @param $file
     * @return void
     */
    public function importExcel($file)
    {
        // 使用 maatwebsite/excel 包来读取 Excel 文件
        $data = Excel::toCollection(null, $file);
        try {
            foreach ( $data as $key => $sheetData ) {
                try {
                    $insertData = [];
                    foreach ( $sheetData as $index => $item ) {
                        if ($index == 0) {
                            continue;
                        }
                        $paperId = $item[6] ?? null;
                        if (! $paperId) {
                            continue;
                        }
                        $paperId = str_replace("\n", "", $paperId);
                        if (! str_starts_with((string)$paperId, "2")) {
                            continue;
                        }
                        if (isset($importPaperListByPaperId[$paperId])) {
                            continue;
                        }
                        // if (! ctype_digit($item[2] ?? 0)) {
                        //     continue;
                        // }
                        $insertData[] = [
                            'paper_id'    => $paperId,
                            'sheet'       => $key,
                            'author'      => $item[3] ?? '',
                            // 'num'         => $item[2] ?? 0,
                            // 'title'       => $item[1] ?? '',
                            'create_time' => date('Y-m-d H:i:s', 1723133461)
                        ];
                    }
                    if (! $insertData) {
                        continue;
                    }
                    DB::connection('test')->table('import')->insert($insertData);
                    DB::commit();
                } catch (\Throwable $exception) {
                    Log::error('队列执行失败:'.$exception->getMessage().'文件路径:'.$file.',sheet数目:'.$key);
                    DB::rollBack();
                }
            }

        } catch (\Throwable $exception) {
            Log::error('队列执行失败:'.$exception->getMessage().'文件路径:'.$file);

            return;
        }
    }

    /**
     * 同步试卷数据
     * @param array $paperIds
     * @return bool
     */
    public function syncPaperData(array $paperIds = []): bool
    {
        // 开始事务
        DB::beginTransaction();

        try {
            $addPaperIds = $this->insertPapers($paperIds);

            $this->insertTopic($addPaperIds);

            $this->insertPaperRelatedRecords('paper_area', $addPaperIds);

            $this->insertPaperRelatedRecords('single_topics_paper', $addPaperIds);

            DB::connection('test')->table('import')
              ->whereIn('paper_id', $paperIds)
              ->update(['status' => 1]);

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            Log::error('队列执行失败:'.$exception->getMessage().'paper_ids:'.json_encode($paperIds));

            return false;
        }

        return true;

    }

    /**
     * 插入试卷信息
     * @param array $paperIds
     * @return array
     */
    protected function insertPapers(array $paperIds = []): array
    {
        $newPaperIds = [];
        foreach ( $paperIds as $paperId ) {
            $flag = $this->insertPaperRecords('papers', $paperId);
            if ($flag !== false) {
                $newPaperIds[] = $flag;
            }
        }

        return $newPaperIds;

        // 批量插入试卷相关记录
        // $this->insertPaperRelatedRecords('paper_area', $paperIds);

        // $this->insertPaperRelatedRecords('single_topics_paper', $paperIds);
    }

    /**
     * 插入题库
     * @param array $paperIds
     * @return bool
     */
    protected function insertTopic(array $paperIds = []): bool
    {
        $singleTopicIds = DB::table('single_topics_paper')
                            ->whereIn('paper_id', $paperIds)
            // ->whereNotIn('paper_id', $hasPaperIds)
                            ->pluck('single_topic_id')
                            ->toArray();

        $singleTopicIds = array_unique($singleTopicIds);

        $singleTopics = DB::table('single_topics')
                          ->whereIn('id', $singleTopicIds)
                          ->get();

        foreach ( $singleTopics as $singleTopic ) {
            $exists = DB::connection('test')->table('single_topics')
                        ->select('id')
                        ->where('id', $singleTopic->id)
                        ->first();

            if ($exists) {
                continue;
            }

            DB::connection('test')->table('single_topics')->insert((array)$singleTopic);

            $this->insertRelatedRecords('single_topic_option', $singleTopic->id);

            $this->insertRelatedRecords('single_topics_knowledge_points', $singleTopic->id);

            $this->insertRelatedRecords('single_topics_source', $singleTopic->id);

            $this->insertRelatedRecords('single_topics_use_zone', $singleTopic->id);
        }

        return true;
    }

    /**
     * 插入试题关联
     * @param $table
     * @param $singleTopicId
     * @return void
     */
    protected function insertRelatedRecords($table, $singleTopicId)
    {
        $relatedRecords = DB::table($table)
                            ->where('single_topic_id', $singleTopicId)
                            ->get();

        foreach ( $relatedRecords as $record ) {
            DB::connection('test')->table($table)->insert((array)$record);
        }
    }


    /**
     * 插入试卷
     * @param $table
     * @param $paperId
     * @return bool|void
     */
    protected function insertPaperRecords($table, $paperId)
    {
        $relatedRecords = DB::table($table)
                            ->where('id', $paperId)
                            ->first();
        if (! $relatedRecords) {
            return false;
        }
        $paper = DB::connection('test')->table($table)
                   ->select('id')
                   ->where('id', $paperId)
                   ->first();
        if ($paper) {
            return false;
        }
        DB::connection('test')->table($table)->insert((array)$relatedRecords);

        return $relatedRecords->id;
    }

    /**
     * 插入试卷关联
     * @param $table
     * @param $paperId
     * @return void
     */
    protected function insertPaperRelatedRecords($table, $paperId)
    {
        $relatedRecords = DB::table($table)
                            ->whereIn('paper_id', $paperId)
                            ->get();

        foreach ( $relatedRecords as $record ) {
            DB::connection('test')->table($table)->insert((array)$record);
        }
    }


    /**
     * 删除
     * @param array $paperIds
     * @return false|void
     */
    public function deletePaperData(array $paperIds = [])
    {
        // 开始事务
        DB::beginTransaction();

        try {
            $this->deleteSingleTopic($paperIds);

            $this->deletePaperRecords('papers', $paperIds);

            DB::connection('test')->table('import')
              ->whereIn('paper_id', $paperIds)
              ->update(['status' => -1]);

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            Log::error('队列执行失败:'.$exception->getMessage().'paper_ids:'.json_encode($paperIds));

            return false;
        }

        return true;

    }

    /**
     * 删除试题
     * @param array $paperIds
     * @return bool
     */
    protected function deleteSingleTopic(array $paperIds = []): bool
    {
        $singleTopicIds = DB::table('single_topics_paper')
                            ->whereIn('paper_id', $paperIds)
                            ->pluck('single_topic_id')
                            ->toArray();
        $singleTopicIds = array_unique($singleTopicIds);

        $deleteTopicIds = [];
        foreach ( $singleTopicIds as $singleTopic ) {
            $singleTopicId = $singleTopic;
            $exists = DB::connection('test')->table('single_topics_paper')
                        ->select('single_topic_id')
                        ->whereNotIn('paper_id', $paperIds)
                        ->where('single_topic_id', $singleTopicId)
                        ->first();
            if ($exists) {
                continue;
            }

            DB::connection('test')->table('single_topics')->where('id', $singleTopicId)->delete();

            $deleteTopicIds[] = $singleTopicId;
        }

        $this->deleteRelatedRecords('single_topic_option', $deleteTopicIds);

        $this->deleteRelatedRecords('single_topics_knowledge_points', $deleteTopicIds);

        $this->deleteRelatedRecords('single_topics_source', $deleteTopicIds);

        $this->deleteRelatedRecords('single_topics_use_zone', $deleteTopicIds);

        return true;
    }

    /**
     * @param $table
     * @param $singleTopicId
     * @return void
     */
    protected function deleteRelatedRecords($table, $singleTopicId)
    {
        DB::connection('test')->table($table)->whereIn('single_topic_id', (array)$singleTopicId)->delete();
    }

    /**
     * 删除
     * @param $table
     * @param array $paperIds
     * @return bool
     */
    protected function deletePaperRecords($table, array $paperIds = []): bool
    {
        DB::connection('test')->table($table)
          ->whereIn('id', $paperIds)
          ->delete();

        $this->deletePaperRelatedRecords('paper_area', $paperIds);

        $this->deletePaperRelatedRecords('single_topics_paper', $paperIds);

        return true;
    }

    /**
     * 删除试卷
     * @param $table
     * @param $paperId
     * @return void
     */
    protected function deletePaperRelatedRecords($table, $paperId)
    {
        DB::connection('test')->table($table)->whereIn('paper_id', (array)$paperId)->delete();
    }
}